require 'net/http'
require 'rexml/document'

=begin
 * Author: Max Aller
 * Date: April 20, 2008
=end
class CurrencyConverter
  @@data = nil
  
  DATA_URL = 'http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml'
  
=begin
  Amount is a currency amount, and from and to are "USD", "MXN", "JPY", etc.
  Call get_available_currencies to see all the currencies.
=end
  def CurrencyConverter.convert(amount, from, to, places=2)
    load_data if @@data.nil?
    
    raise ArgumentError, to.to_s + " not a valid currency (for 'to')." if @@data[to].nil?
    raise ArgumentError, from.to_s + " not a valid currency (for 'from')." if @@data[from].nil?
    
    (amount.to_f * (@@data[to] / @@data[from])).round(places)
  end
  
  def CurrencyConverter.get_available_currencies
    load_data if @@data.nil?
    
    return @@data.keys.sort
  end
  
  private
  def CurrencyConverter.load_data
    begin
      xml_data = Net::HTTP.get_response(URI.parse(DATA_URL)).body
  
      doc = REXML::Document.new(xml_data)
      @@data = {}
        
      doc.root.elements.each('Cube/Cube/Cube') do |el|
        @@data[el.attribute('currency').value] = el.attribute('rate').value.to_f
      end
      @@data['EUR'] = 1.0000
    rescue REXML::ParseException
      raise $!
    end
  end
end